package com.itic.appbase.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.itic.appbase.framework.common.basevo.User;
import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.SessionTimeoutException;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;

/**
 * Session有效性拦截器. 拦截URI并
 * 
 * @ClassName: SessionValidInterceptor
 * @author: djp_ivan
 * @date: Apr 15, 2015 11:26:03 AM
 * @version: V1.0
 * @Update_Comments: by djp_ivan at Apr 15, 2015 - description
 */
public class SessionValidInterceptor
        extends BaseController
        implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        boolean result = true;
        // 配置本地User Session Helper
        User user = this.findUserSession(request);
        if (null == user || StringHelper.isEmpty(user.getId())) {
            result = false;
            throw new SessionTimeoutException("session timeout!");
        } else {
            // UserSessionHelper 设置
            UserSessionHelper.set(Constants.USER_ID, user.getUserId());
            UserSessionHelper.set(Constants.USER_ORG, user.getOrganizationCode());
        }
        return result;
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView)
            throws Exception {
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
